package com.yueze.demo1.util;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
/**
 * @author Administrator
 * @create 2020-07-28
 * 13:37
 * @desc 图片截取类
 **/

public class PicCut {
    public void cut(int x, int y, int width, int height, String srcpath, String subpath) throws IOException {//裁剪方法
        FileInputStream is = null;
        ImageInputStream iis = null;
        try {
            is = new FileInputStream(srcpath); //读取原始图片
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpeg"); //ImageReader声称能够解码指定格式
            ImageReader reader = it.next();
            iis = ImageIO.createImageInputStream(is); //获取图片流
            reader.setInput(iis, true); //将iis标记为true（只向前搜索）意味着包含在输入源中的图像将只按顺序读取
            ImageReadParam param = reader.getDefaultReadParam(); //指定如何在输入时从 Java Image I/O框架的上下文中的流转换一幅图像或一组图像
            Rectangle rect = new Rectangle(x, y, width, height); //定义空间中的一个区域
            param.setSourceRegion(rect); //提供一个 BufferedImage，将其用作解码像素数据的目标。
            BufferedImage bi = reader.read(0, param); //读取索引imageIndex指定的对象
            ImageIO.write(bi, "jpeg", new File(subpath)); //保存新图片
        } finally {
            if (is != null)
                is.close();
            if (iis != null)
                iis.close();
        }
    }

    public static void main(String[] args) {
        PicCut picCut = new PicCut();
        String pre = "C:\\javaproject\\siruan\\save\\22.jpeg";
        String fix = "C:\\javaproject\\siruan\\save\\33.jpeg";
        try {
            picCut.cut(50,50,200,200,pre,fix);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}